﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Interop;

namespace Wallpaper.Class
{
    public static class FormsControl
    {
        private static IntPtr FatherForm = IntPtr.Zero;

        public static bool SetBottom(Window window)
        {
            try
            {
                FatherForm = GetBackForm();
                if(FatherForm == IntPtr.Zero)
                {
                    return false;
                }
                else
                {
                    int result = DllImpoter.SetParent(new WindowInteropHelper(window).Handle, FatherForm);
                    return result == 1;
                }
            }
            catch (Exception e)
            {
                return false;
            }
        }

        public unsafe static IntPtr GetBackForm()
        {
            IntPtr background = IntPtr.Zero;
            IntPtr father = DllImpoter.FindWindow("progman", "Program Manager");
            IntPtr workerW = IntPtr.Zero;
            DllImpoter.SendMessage(father, 0x052C, IntPtr.Zero, null);
            do
            {
                workerW = DllImpoter.FindWindowEx(IntPtr.Zero, workerW, "workerW", null);
                if (workerW != IntPtr.Zero)
                {
                    char[] buff = new char[200];
                    IntPtr b = Marshal.UnsafeAddrOfPinnedArrayElement(buff, 0);
                    int ret = (int)DllImpoter.GetClassName(workerW, b, 400);
                    if (ret == 0) return IntPtr.Zero;
                }
                if (DllImpoter.GetParent(workerW) == father)
                {
                    background = workerW;
                }
            } while (workerW != IntPtr.Zero);
            return background;
        }

        public static void RefreshBackground()
        {
            StringBuilder sb = new StringBuilder(200);
            DllImpoter.SystemParametersInfo(0x73, 200, sb, 0);
            int ret = DllImpoter.SystemParametersInfo(20, 1, sb, 3);
            if (ret != 0)
            {
                RegistryKey hk = Registry.CurrentUser;
                RegistryKey run = hk.CreateSubKey(@"Control Panel\Desktop\");
                run.SetValue("Wallpaper", sb.ToString());
            }
        }

        public static void test()
        {
            DllImpoter.SendMessage((IntPtr)FatherForm, 0x000F, (IntPtr)0, null);
        }
    }
}
